package com.ncu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ncu.gulimall.auth.feign.MemberFeignService;
import com.ncu.gulimall.common.vo.MemberRespVo;
import com.ncu.gulimall.auth.vo.SocialUser;
import com.ncu.gulimall.common.utils.HttpUtils;
import com.ncu.gulimall.common.utils.R;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        // 1、根据code换区access_token
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id", "530142196");
        map.put("client_secret", "45d15c625c71312d53eeef60c69477e1");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);

        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String, String>(), null, map);
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            // 如果当前用户是第一次进，则自动注册（为当前社交用户生成会员信息账号，以后当前社交账号与该会员信息绑定）
            R r = memberFeignService.oauthlogin(socialUser);
            if (r.getCode() == 0) {
                // 2、登录成功跳回首页
                MemberRespVo memberRespVo = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                //  放大作用域，解决子域session共享问题
                //  使用json方式序列化存储进redis（默认的jdk方式不方便）
                session.setAttribute("loginUser", memberRespVo);
//                System.out.println("memberRespVo = " + memberRespVo);
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
